package com.estun.backroundManagementService.modules.material.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.estun.backroundManagementService.config.CustomApiException;
import com.estun.backroundManagementService.config.factoryMes.ApiCaller;
import com.estun.backroundManagementService.config.properties.ApiInfoProperties;
import com.estun.backroundManagementService.config.properties.LineInfoProperties;
import com.estun.backroundManagementService.domain.BaseResponse;
import com.estun.backroundManagementService.domain.factoryMes.request.ManualMaterialCallingRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesResponse;
import com.estun.backroundManagementService.modules.material.mapper.ManualMaterialCallingMapper;
import com.estun.backroundManagementService.modules.material.model.ManualMaterialCalling;
import com.estun.backroundManagementService.modules.material.service.ManualMaterialCallingService;
import com.estun.backroundManagementService.modules.workOrder.service.WorkOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@AllArgsConstructor
public class ManualMaterialCallingServiceImpl extends ServiceImpl<ManualMaterialCallingMapper, ManualMaterialCalling> implements ManualMaterialCallingService {


    private final ApiCaller apiCaller;
    private final ApiInfoProperties apiInfoProperties;
    private final LineInfoProperties lineInfoProperties;
    private final WorkOrderService workOrderService;

    @Override
    public BaseResponse manualMaterialCalling(ManualMaterialCallingRequest req) {
        BaseMesRequest<ManualMaterialCallingRequest> request = new BaseMesRequest<>();
        request.getData().add(req);
        ManualMaterialCalling result = new ManualMaterialCalling();
        BeanUtils.copyProperties(req, result);
        BaseMesResponse mesResponse = new BaseMesResponse<>();
        try {
            mesResponse = apiCaller.post(apiInfoProperties.getManualMaterialCalling(), request, BaseMesResponse.class);
        } catch (CustomApiException exception) {
            mesResponse.setFail(true);
            mesResponse.setSuccess(false);
            mesResponse.setMesg(exception.getMessage());
        }
        result.setLineCode(lineInfoProperties.getLineCode());
        result.setScheduleCode(workOrderService.getInProcessSchedule().getScheduleCode());
        result.setMessage(mesResponse.getMesg());
        if (mesResponse.isSuccess()) {
            result.setResult(1);
            save(result);
            return BaseResponse.success("叫料成功");
        } else {
            result.setResult(0);
            save(result);
            return BaseResponse.error("叫料失败:" + mesResponse.getMesg());
        }
    }
}
